﻿
using System.Text.RegularExpressions;

namespace EventBusNet6;

public class LibreOfficeService : ILibreOfficeService
{

    private string OutPutDir = string.Empty;
    private string ExePath = string.Empty;
    private string NoticeUrl = string.Empty;
    public LibreOfficeService(IOptions<LibreOfficeOptions> libreOfficeOptions)
    {
        string basePath = AppContext.BaseDirectory;
        ExePath = Path.Combine(basePath, libreOfficeOptions.Value.ExePath ?? "");
        NoticeUrl = libreOfficeOptions.Value.NoticeUrl ?? "";
        OutPutDir = libreOfficeOptions.Value.OutPutDir ?? "";

        var path = "{yyyy}{MM}\\{dd}";
        if (string.IsNullOrWhiteSpace(OutPutDir))
        {
            var reg = new Regex(@"(\{.+?})");
            var match = reg.Matches(path);
            match.ToList().ForEach(a =>
            {
                var str = DateTime.Now.ToString(a.ToString().Substring(1, a.Length - 2)); // 每天一个目录
                path = path.Replace(a.ToString(), str);
            });
            OutPutDir = Path.Combine(basePath, path);
        }
    }

    public string ConvertFirstJpg(string inputPath, string guid)
    {
        StringBuilder stringBuilder = new StringBuilder();
        string outputPath = Path.Combine(OutPutDir, guid);
        stringBuilder.Append($"soffice --headless --invisible --convert-to jpg {inputPath} --outdir {outputPath}");
        var cmd = new ExecuteCommand(stringBuilder.ToString(), outputPath, ExePath, NoticeUrl, guid,"first.jpg");
        CommandService.GetInstance().Add(cmd);

        return outputPath;
    }

    public string ConvertPDF(string inputPath, string guid)
    {
        //soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile 
        //libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile
        StringBuilder stringBuilder = new StringBuilder();
        string outputPath = Path.Combine(OutPutDir, guid);
        if (!Directory.Exists(outputPath))
        {
            Directory.CreateDirectory(outputPath);
        }
        stringBuilder.Append($"soffice --headless --invisible --convert-to pdf:writer_pdf_Export {inputPath} --outdir {outputPath}");
        var cmd = new ExecuteCommand(stringBuilder.ToString(), outputPath, ExePath, NoticeUrl, guid,"conver.pdf");
        CommandService.GetInstance().Add(cmd);
        return outputPath;
    }
}
